package com.share.common.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ObjUtil {

    /*复制对象的属性到新的对象*/
    public static <T> T copy(Object from, Class<T> to) {
        String s = JSON.toJSONString(from);
        return JSON.parseObject(s, to);
    }

    //值为空的不要返回
    public static Map<String, Object> toMapIgnoreNull(Object obj) {
        return toMap(obj, true);
    }

    public static int keySize(Object obj) {
        if (obj == null) {
            return -1;
        } else {
            return toMap(obj, false).keySet().size();
        }
    }

    //值为空计数
    public static int keySizeIgnoreNull(Object obj) {
        if (obj == null) {
            return -1;
        } else {
            return toMap(obj, true).values().size();
        }
    }

    //值为空也返回
    public static Map<String, Object> toMap(Object obj) {
        return toMap(obj, false);
    }

    /*对象转map*/
    public static Map<String, Object> toMap(Object obj, boolean ignoreNull) {
        if (obj == null) {
            return new HashMap<>();
        } else {
            return Arrays.stream(BeanUtils.getPropertyDescriptors(obj.getClass()))
                    .filter(itm -> !"class".equals(itm.getName()))
                    .collect(HashMap::new,
                            (map, pd) -> {
                                Object value = ReflectionUtils.invokeMethod(pd.getReadMethod(), obj);
                                if (ignoreNull) {
                                    if (value != null) {
                                        map.put(pd.getName(), value);
                                    }
                                } else {
                                    map.put(pd.getName(), value);
                                }
                            },
                            HashMap::putAll);
        }
    }

    /*对象转key参数*/
    public static String toKv(Object obj) {
        StringBuffer sb = new StringBuffer();
        Class clazz = obj.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            String name = field.getName();
            sb.append("&" + name + "=");
            String methodName = "get" + name.toUpperCase().substring(0, 1) + name.substring(1);
            Object invoke = null;
            try {
                invoke = clazz.getMethod(methodName).invoke(obj);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (invoke != null) {
                sb.append(invoke.toString());
            }
        }

        if (sb.length() > 0) {
            sb.deleteCharAt(0);
        }

        return sb.toString();
    }
}
